package com.guet.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.guet.domain.Follow;
import com.guet.domain.dto.UserDTO;
import com.guet.mapper.FollowMapper;
import com.guet.service.FollowService;
import com.guet.service.UserService;
import com.guet.utils.Result;
import com.guet.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class FollowServiceImpl implements FollowService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private FollowMapper followMapper;
    @Resource
    private UserService userService;

    @Override
    public Result follow(Long id, Boolean isFollow) {
        // userId关注> id
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;

        if(isFollow){
            // 关注
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(id);
            boolean isSuccess = followMapper.save(follow);
            if(isSuccess){
                stringRedisTemplate.opsForSet().add(key,id.toString());
            }
        } else {
            // 取关
            boolean isSuccess = followMapper.delete(userId,id);
            if(isSuccess){
                stringRedisTemplate.opsForSet().remove(key,id.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long id) {
        Long userId = UserHolder.getUser().getId();
        Integer count = followMapper.isFollow(userId,id);
        return Result.ok(count > 0);
    }

    @Override
    public Result followCommons(Long id) {
        // 当前用户
        Long userId = UserHolder.getUser().getId();
        String key = "follows:" + userId;
        // 目标用户
        String key2 = "follows:" + id;
        // 交集
        Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
        if(intersect == null || intersect.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> users = userService.getByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(users);
    }

    @Override
    public List<Follow> getFans(Long followUserId){
        // 查询followUserId这个人的所有粉丝 (即谁关注了followUserId)
        List<Follow> fans = followMapper.getFans(followUserId);
        return fans;
    }
}
